<!--
*@Author: QWP
*@Description: 出差申请编辑
*@Date: 2023-09-12 11:03:29
-->
<template>
  <u-dialog v-bind="$attrs" v-on="$listeners" :hideBtns="isCheck || getCanEdit == false ? ['confirm'] : []" v-helpD="{
    value: showHelp,
    width: $attrs.width || '65%',
    fullscreen: $attrs['fullscreen'],
  }" @full="showHelp = false" @submit="submit" @close="dialogClose">
    <template slot="headerTool">
      <u-help-icon :pshow="$attrs['show']" busiType="evectionInput" @click.native="showHelp = !showHelp" />
    </template>

    <el-main class="u-container">
      <u-busi-item class="clear f-padding-0 u-progress" style="background-color: unset">
        <u-step :active="active" align-center finish-status="success" :data="stepData" />
      </u-busi-item>
      <u-loading-box class="u-content" :loading="loading">
        <u-busi-item class=" f-h-100">

          <u-form :elements="elements" v-bind="$attrs" :model="form" ref="form" :disabled="!getCanEdit || isCheck"
            @focus="focusinput">
            <!-- 预计起止时间 -->
            <template slot="rangeDate">
              <el-row>
                <el-col>
                  <u-date-picker v-model="form.rangeDate" :data="regionData" range-separator="-" type="daterange"
                    start-placeholder="开始时间" end-placeholder="结束时间" />
                </el-col>
              </el-row>
            </template>
            <!-- 往返地点 -->
            <template slot="fkareaidstart">
              <el-row>
                <el-col :span="11">
                  <u-cascader v-model="form['fkareaidstart']" :data="regionData" />
                </el-col>
                <el-col :span="2" style="text-align: center">
                  至
                </el-col>
                <el-col :span="11">
                  <u-cascader ref="areaIdEnd" v-model="form['fkareaidend']" :data="regionData" />
                </el-col>
              </el-row>
            </template>
          </u-form>
          <u-edit-table :columns="getFileCols" :data="fileData" :isCheck="[2, 3].includes(params['status']) || isCheck"
            :fileParams="{
              biztype: '2',
              bucket: 'FIN_BIZ_TYPE',
              moduletype: 'FIN',
            }" height="100%" />

        </u-busi-item>
      </u-loading-box>
    </el-main>

    <!-- 保存成功 -->
    <div v-if="showconfirm && isIndex" class="confirm-box">
      <div class="confirm-box-content">
        <img src="../../../assets/fillingOfficerIcon/完成.png" />
        <p style="
            margin: 12px 0 12px 201px;
            font-size: 14px;
            font-weight: 400;
            color: #1d2129;
          ">
          保存成功
        </p>
        <p style="margin: 12px 0 12px 150px">报销信息填写完成，是否关闭</p>
        <p style="margin: 12px 0 32px 160px">当前页面还是返回列表页面</p>
        <el-button style="margin: 0px 0 0px 100px" class="f-fl" type="info" size="small"
          @click="dialogShow = false">关闭当前页面
        </el-button>
        <el-button style="margin-right: 16px" class="f-fr" type="primary" size="small" @click="torouterMx">返回列表页
        </el-button>
      </div>
    </div>

    <template slot="footer">
      <u-ptype-button itype="print" v-if="form.status" @click="toPrint"> 打印出差审批单</u-ptype-button>
      <template v-if="[1, 4].includes(form['status']) && !isAuditPage && !noEdit">
        <u-ptype-button itype="report" @click="saveFlow">提交审核
        </u-ptype-button>
      </template>
      <template v-else-if="getIsAudit && !noEdit">
        <u-ptype-button itype="audit" @click="toAudit(1)">通过</u-ptype-button>
        <u-ptype-button itype="back" @click="toAudit(2)" danger>退回</u-ptype-button>
      </template>
    </template>

    <!-- 帮助文档 -->
    <template slot="other">
      <u-help v-if="showHelp" type="travelApply" @close="showHelp = false" />
    </template>

    <dyccd-dialog :show="dyccdShow" @close="dyccdShow = false" />

    <!-- 出差人员弹窗 -->
    <cc-people :show="evectionUserShow" :checkUsers="form.users" width="85%" @save="evectionSubmit"
      @close="evectionUserShow = false" />

    <!-- 出差费用 -->
    <cc-fy-dialog :show="ccfyDailogShow" @close="ccfyDailogShow = false" />

    <!-- 提交审核 -->
    <u-submit-audit :show="showSubmitAudit" :params="{ ...params, ...getTypesFounds, ...form }" :directSave="false"
      ref="saveFlow" @close="showSubmitAudit = false" @save="submit" @success="submitSuccess" />

    <!-- 审核或退回 -->
    <u-audit :show="showAudit" :params="params" ref="audit" @close="showAudit = false" @success="submitSuccess" />

    <!-- 出差审批表 -->
    <u-evection-print :form="printForm" id="evectionPrint" v-show="showPrintEl" />
  </u-dialog>
</template>
<script>
import dyccdDialogVue from './components/dyccdDialog.vue';
import jbxxFormVue from './components/jbxxForm.vue';
import ccfyDialogVue from './components/ccfyDialog.vue';
import ccPeople from './components/ccPeople.vue';
import Evection_print from '@/components/busi/dailyComponents/print/Evection_print.vue';
import { fileCols } from '@/common/model/fileCols';
import { print } from '@/util/print_tool';
import enmuService from '@/service/common/enmu.service';
import evection_applyService from '@/service/busi/finance/evection_apply.service';
import evection_regionService from '@/service/busi/finance/evection_region.service';
import constance_contact from '@/service/busi/finance/constance_contact';
import userService from '@/service/system/user.service';
import auditService from '@/service/common/audit.service';
import reimburseService from '@/service/busi/finance/reimburse.service';
import { formatAuditUserSign, getItemByIds } from '@/util/format.ts'
import { createNamespacedHelpers } from 'vuex';
import { alertC, isValue, nullC, numberC, jsonCopy } from '@/util/common';
import dayjs from 'dayjs';

const { mapGetters } = createNamespacedHelpers('loginStore');
const { mapGetters: homeGetters, mapMutations: homeMutations } =
  createNamespacedHelpers('homeStore');
export default {
  components: {
    'jbxx-form': jbxxFormVue,
    'dyccd-dialog': dyccdDialogVue,
    'cc-people': ccPeople,
    'cc-fy-dialog': ccfyDialogVue,
    'u-evection-print': Evection_print
  },
  props: {
    isCheck: {
      type: Boolean,
      default: false
    },

    isIndex: {
      // 是否是首页进来的
      type: Boolean,
      default: false
    },

    noEdit: {
      // 是否不允许按钮操作
      type: Boolean,
      default: false
    },

    params: {
      type: Object,
      default: () => {
      }
    }
  },
  data () {
    return {
      active: 0,
      stepData: [
        { title: '经办人填报', description: '填写相关出差信息' },
        { title: '数据审核', description: '出差申请审核中' },
        { title: '审核完成', description: '数据审核完毕' }
      ],

      t: '',

      evectionUserShow: false,
      ccfyDailogShow: false,

      loading: false,
      dyccdShow: false,
      showconfirm: false,
      form: {
        redeptname: '',
        fkusername: '',
        tel: '',
        evectiondate: dayjs(new Date()).format('YYYY-MM-DD'),
        traveltype: '',
        evectionuser: '',
        total: 0,
        travelway: '',
        fkareaidstart: '1780067802108497922',
        fkareaidend: '',
        startdate: '',
        enddate: '',
        typeOfFunds: [],
        evectionamount: 0,
        evectionreason: '',
        users: [],
        keyid: '',
        fkuserid: '',
        fkunitsid: '',
        status: '',
        fkareacodeend: '',
        rangeDate: ''
      },
      elements: [
        { element: 'text', label: '申请部门', span: 8, key: 'redeptname' },
        { element: 'text', label: '申请人', span: 8, key: 'fkusername' },
        { element: 'text', label: '申请人电话', span: 8, key: 'tel' },
        { element: 'datepicker', label: '填报日期', span: 8, key: 'evectiondate', required: true },
        { element: 'input', label: '出差人员', span: 8, key: 'evectionuser', readonly: true, required: true },
        { element: 'input', label: '本次出差总人数', span: 8, key: 'total', disabled: true },
        {
          element: 'select', label: '出差类型', span: 8, key: 'traveltype',
          data: this.$store.getters['baseStore/get_TRAVEL_TYPE'], required: true
        },
        { element: 'slot', span: 8, key: 'fkareaidstart', required: true, label: '往返地点' },
        {
          element: 'select', label: '出行方式', span: 8, key: 'travelway',
          data: this.$store.getters['baseStore/get_TRAVEL_APPLY_WAY'], required: true
        },
        { element: 'slot', key: 'rangeDate', type: 'daterange', label: '预计起止时间', span: 8, required: true, },
        {
          element: 'select', label: '经费来源', span: 8, key: 'typeOfFunds', required: true,
          data: this.$store.getters['baseStore/get_TYPE_OF_FUNDS'], multiple: true
        },
        { element: 'money', label: '预计费用', span: 8, key: 'evectionamount', append: '元', required: true },
        {
          element: 'input', type: 'textarea', label: '出差事由', span: 24, key: 'evectionreason',
          required: true, 'show-word-limit': true, maxlength: 200
        }
      ],
      regionData: this.$store.getters['baseStore/get_EVECTION_AREA'],

      fileData: [],

      showHelp: false,

      // 审核
      showSubmitAudit: false,
      showAudit: false,

      printForm: {},
      showPrintEl: false
    };
  },
  computed: {
    // 该审核人id和登录人id是否是同一个人
    getIsAudit () {
      return this.getUserInfo['userId'] == this.params['fkaudituserid'];
    },
    // 能不能编辑 录入 和 退回
    getCanEdit () {
      return [1, 4].includes(this.params['status']) || !this.params['status'];
    },
    isAuditPage () {
      if (this.$route.name) {
        return this.$route.name == 'TravelRequestAudit';
      }
      return false;
    },
    getTypesFounds () {
      let tform = JSON.parse(JSON.stringify(this.form));
      return tform.typeOfFunds instanceof Array
        ? { typeOfFunds: tform.typeOfFunds.join(',') }
        : {};
      return {};
    },
    getFileCols () {
      return fileCols(!this.getCanEdit);
    },
    ...mapGetters(['getUserInfo']),
    ...homeGetters(['getTabMenu'])
  },
  mounted () {
  },
  methods: {
    ...homeMutations(['setTabMenu']),

    // 设置默认的出差人
    async initSetEvection () {
      this.$set(this.form, 'fkunitsid', this.getUserInfo['unitId']);
      this.$set(this.form, 'fkuserid', this.getUserInfo['userId']);
      this.$set(this.form, 'redeptname', this.getUserInfo['deptName']);
      this.$set(this.form, 'fkusername', this.getUserInfo['name']);
      this.$set(this.form, 'tel', this.getUserInfo['tel']);
      this.$set(this.form, 'total', 1);
      this.$set(this.form, 'evectionuser', this.getUserInfo['name']);
      let isCommon = -1;

      const data = await constance_contact.queryByUserId(
        nullC(this.$store.getters['loginStore/getUserInfo']['userId'])
      );

      if (data.data.code == 0) {
        isCommon = data.data.data.findIndex(
          (item) => item.fkcontactuserid == this.getUserInfo['userId']
        );
      }
      let users = [
        {
          fkdeptid: this.getUserInfo['deptId'],
          fkuserid: this.getUserInfo['userId'],
          isdriver: 0,
          orderno: 0,
          isconstance: isCommon == -1 ? '0' : '1',
          redeptname: this.getUserInfo['deptName'],
          reusername: this.getUserInfo['name']
        }
      ];
      this.$set(this.form, 'users', users);
    },

    // 保存提交
    submit (callbck) {
      this.$refs.form.$refs.form.validate(async (vali) => {
        if (!vali) {
          alertC('请现将必填项填写完毕！');
          return;
        }

        if (
          !isValue(this.form.fkareaidstart) ||
          !isValue(this.form.fkareaidend)
        ) {
          alertC('请先将往返地点填写完毕！');
          return;
        }

        const tform = JSON.parse(JSON.stringify(this.form));
        // tform.startdate = this.form.startdate[0]
        // tform.enddate = this.form.startdate[1]

        // 单位派车应有司机
        if (this.form.travelway == 1) {
          let isHaveDriver = this.form.users.every(
            (item) => item.isdriver == 0
          );
          if (isHaveDriver) {
            alertC('出行方式为【单位派车】时请确认司机!');
            return;
          }
        } else {
          const userS = JSON.parse(JSON.stringify(this.form['users'] || []));
          let haveDriver = userS.some((item) => item['isdriver'] == 1);
          if (haveDriver) {
            alertC('当前出行方式不是单位派车，请取消司机勾选！');
            return;
          }
        }

        // 附件数据
        tform.appendix = this.fileData
          .map((item, index) => {
            return {
              ...item.appendix,
              filename: item.filename,
              filepath: item.filepath,
              orderno: index
            };
          })
          .filter((item) => isValue(item['filepath']));

        if (tform.typeOfFunds instanceof Array) {
          tform.typeOfFunds = tform.typeOfFunds.join(',');
        }

        tform.startdate = tform.rangeDate[0];
        tform.enddate = tform.rangeDate[1];

        const url = isValue(this.params['keyid']) || isValue(this.form['keyid']) ? 'update' : 'add';

        this.loading = true;
        evection_applyService[url](tform)
          .then((res) => {
            this.loading = false;
            if (res.data.code == 0) {
              this.isIndex == true ? (this.showconfirm = true) : this.$emit('success');
              this.$set(this.form, 'status', res.data.data['status']);
              if (url == 'add') {
                this.form.keyid = nullC(res.data.data['keyid']);
                this.$emit('addSuccess', res.data.data);
                alertC(res.data.msg, 'success');
              }
              if (!callbck) {
                alertC(res.data.msg, 'success');
              } else {
                callbck(res);
              }
            } else {
              alertC(res.data.msg, 'warning');
            }
          })
          .catch(() => (this.loading = false));
      });
    },

    // 回显信息
    async getEcho () {
      this.loading = true;
      await evection_applyService
        .singleQuery(this.params['keyid'])
        .then((res) => {
          this.loading = false;
          if (res.data.code == 0) {

            // 打印数据
            this.printForm = res.data.data;
            this.setUpdateParams(jsonCopy(res.data.data));
            this.getAuditInfo();

            // 获取当前的数据流程
            this.getBusiStep(res.data.data);
            for (let key in this.form) {
              if (isValue(res.data.data[key])) {
                this.$set(this.form, key, res.data.data[key]);
              }
            }

            if (this.form.typeOfFunds) {
              this.form.typeOfFunds = this.form.typeOfFunds
                .split(',')
                .map((i) => numberC(i));
            }

            // 出差方式、出差类型
            this.form.traveltype = nullC(this.form.traveltype);
            this.form.travelway = nullC(this.form.travelway);

            // 往返地区
            this.form.fkareaidstart = nullC(this.form.fkareaidstart) + '';
            this.form.fkareaidend = nullC(this.form.fkareaidend) + '';

            // 预计起止时间
            this.form.rangeDate = [nullC(this.form.startdate), nullC(this.form.enddate)];

            // 处理出差人和出差个数
            if (res.data.data['users']) {
              this.$set(this.form, 'total', res.data.data['users'].length);

              let reusername = res.data.data['users']
                .map((item) => item.reusername)
                .join(',');
              this.$set(this.form, 'evectionuser', reusername);
            }

            // 附件信息
            if (res.data.data['appendix']) {
              let fdata = res.data.data['appendix'];
              fdata.forEach(
                (item) => (item['appendix'] = JSON.parse(JSON.stringify(item)))
              );
              this.fileData.splice(0, this.fileData.length, ...fdata);
            }
          }
        })
        .catch(() => (this.loading = false));

      userService.singleQuery(this.form.fkuserid).then((res) => {
        if (res.data.code == 0) {
          this.$set(this.form, 'tel', nullC(res.data.data['tel']));
        }
      });
    },

    // 获取审核信息打印
    getAuditInfo () {
      auditService.queryAudit(this.currentData).then(res => {
        this.loading = false;
        if (res.data.code == 0) {
          this.printForm = formatAuditUserSign(res.data.data, jsonCopy(this.printForm));
          this.formatPrintData();
        }
      })
        .catch(() => this.loading = false);
    },

    // 格式化打印数据
    formatPrintData () {
      if (this.printForm.evectiondate) {
        this.printForm.evectiondate = dayjs(this.printForm.evectiondate).format('YYYY年MM月DD日');
      }

      if (this.printForm.fkareaidstart) {
        let tdata = getItemByIds(this.regionData, [this.printForm.fkareaidstart]);
        if (tdata.length != 0) {
          this.printForm.fkareaidstart = tdata[0]['name'];
        }
      }

      if (this.printForm.fkareaidend) {
        let tdata = getItemByIds(this.regionData, [this.printForm.fkareaidend]);
        if (tdata.length != 0) {
          this.printForm.fkareaidend = tdata[0]['name'];
        }
      }

      if (this.printForm.users) {
        this.printForm.eusers = (this.printForm.users || []).map(i => {
          return `${i['reusername']} ${i['isdriver'] == 1 ? '【司】' : ''}`;
        }).filter(i => isValue(i)).join(',');
      }

      if (this.printForm.travelway) {
        let travelWays = this.$store.getters['baseStore/get_TRAVEL_APPLY_WAY'];
        let index = travelWays.findIndex(i => i.id == this.printForm.travelway);
        if (index != -1) {
          this.printForm.travelWay = travelWays[index]['name'];
        }
      }
    },

    // type 1 通过    2 退回
    toAudit (type) {
      this.$refs.audit.form.result = type - 1 + '';
      this.$refs.audit.form.content = type == 1 ? '同意。' : '';
      if (type == 1) {
        this.$refs.audit.submitAudit(true);
      } else {
        this.showAudit = true;
      }
    },

    // 人员选择保存方法
    evectionSubmit (data) {
      this.evectionUserShow = false;
      let names = data.map((item) => item.reusername).join(',');
      let tdata = data;
      tdata.forEach((item, index) => (item.orderno = index));
      this.$set(this.form, 'evectionuser', names);
      this.$set(this.form, 'users', tdata);
      this.$set(this.form, 'total', tdata.length);
    },

    // 基本信息的表单的focus事件
    focusinput (val) {
      if (val == 'evectionuser') {
        this.evectionUserShow = true;
      }
      // 出差费用
      if (val === 'yjfy') {
        // this.ccfyDailogShow = true
      }
    },

    // 提交审核
    saveFlow () {
      if (!['1', '4'].includes(this.form.status + '')) {
        this.$common.alertC('只能提交数据状态为未提交或已退回的数据!');
        return;
      }
      const _this = this;
      this.submit(() => {
        _this.loading = false;
        _this.$refs.saveFlow.batchApply().then(res => {
          _this.loading = false;
          _this.submitSuccess();
        })
          .catch(err => {
            _this.loading = false;
          });
      });
    },

    // 送审成功回调
    submitSuccess () {
      this.showSubmitAudit = false;
      this.showAudit = false;
      setTimeout(() => {
        this.$emit('auditSuccess');
      }, 10);
    },

    // 返回列表
    torouterMx () {
      this.dialogShow = false;
    },

    // 获取业务数据的当前进度
    async getBusiStep (echoInfo = {}) {
      // 没有keyid 为新增填报
      if (!this.params['keyid']) {
        this.active = 0;
        return;
      }

      // 说明已经财务处理；确认科目了
      if ((echoInfo['finTPay'] || {})['accountstatus'] == 2) {
        this.active = this.stepData.length - 1;
        return;
      }

      // 是否有报销数据 fkpayid， 有报销数据则该进入财务处理
      if (echoInfo['fkpayid']) {
        // const bxInfo = await reimburseService.singleQuery(echoInfo['fkpayid'])
        // 如果报销已经审核完成则进入财务处理，如果没有则显示报销
        // this.active = bxInfo.data.data['status'] == 3 ? 3 : 2
        this.active = 3;
      }
      // 审核完成，则该进入报销
      else if ((echoInfo['status'] || '') == 3) {
        this.active = 2;
      }
      // 2 审核中
      else if ((echoInfo['status'] || '') == 2) {
        this.active = 1;
      }
    },

    // 配置修改时，审核需要的参数
    setUpdateParams (data) {
      this.currentData = Object.assign(data,
        {
          amount: numberC(data.evectionamount),
          busType: 2,
          moduleType: 'FIN',
          busId: data['keyid'],
          auditId: data.fkauditid,
          fkareaid: data.fkareaidend
        }
      );
    },

    // 打印出差审批单
    toPrint () {
      let _this = this;
      const inPrint = () => {
        _this.showPrintEl = true;
        _this.printForm = Object.assign(jsonCopy(_this.printForm), _this.form);
        _this.formatPrintData();
        setTimeout(() => {
          print('evectionPrint', function () {
            _this.showPrintEl = false;
          });
        }, 10);
      };
      if (['2', '3'].includes(this.printForm.status + '')) {
        inPrint();
        return;
      }
      this.submit(function () {
        inPrint();
      });
    },

    // 弹窗关闭
    dialogClose () {
      this.showHelp = false;
      this.active = 0;

      for (let key in this.form) {
        this.$set(this.form, key, '');
      }

      this.fileData.splice(0, this.fileData.length);

      this.$set(
        this.form,
        'evectiondate',
        dayjs(new Date()).format('YYYY-MM-DD')
      );
      this.$set(this.form, 'status', '');
      this.$set(this.form, 'total', 0);
      this.$set(this.form, 'users', []);
      this.$set(this.form, 'typeOfFunds', []);
      this.$refs.form.$refs.form.resetFields();
      // this.$set(this.form, 'startdate', [])
    }
  },
  watch: {
    '$attrs.show' (nval) {
      if (nval == true) {
        this.getBusiStep();
        this.initSetEvection();
        if (this.params['keyid']) {
          this.getEcho();
        }
      }
    }
  }
};
</script>
<style lang="scss">
.confirm-box {
  background: #ffffff;
  opacity: 1;
  height: 100%;
  display: flex;

  .confirm-box-content {
    height: 220px;
    width: 400px;
    margin: auto;

    img {
      margin-left: 200px;
    }
  }

  input[element] {
    padding: 3px 0;
  }
}

.u-progress {
  box-shadow: none;
}

.u-container {
  display: flex;
  flex-direction: column;

  .u-content {
    flex-grow: 1;
  }

  .el-table__body-wrapper {
    height: 100% !important;
  }

}
</style>
